/*
 * @Author: yangzonglong
 * @Date: 2021-03-09 16:03:48
 * @version: v1.0.0
 * @Descripttion: 处理select radio 选项设置
 * @LastEditors: yangzonglong
 * @LastEditTime: 2023-07-12 23:10:33
 * @Auditor:
 */
import React, { useCallback, useRef, useState } from 'react';
import { Form, Button, Modal } from 'antd';
import { Formx } from '@library';
import { FormxRefProps } from '@library/components/formx/interface';
import uuid from 'uuid-v4';
import update from 'immutability-helper';
import OptionSettingItem, { LineProps } from './OptionSettingItem';
import Icon from './../../icon/Icon';
import styles from './style.module.scss';

const FormItem = Form.Item,
  dataSourceKey = 'dataSource';

const createDataItem = (dataSource: DataItem[]) => {
  const curTotal = dataSource.length + 1;
  return { label: '未命名' + curTotal, value: 'Value ' + curTotal, key: uuid() };
};

const formItems = [
  {
    name: 'label',
    label: '中文',
  },
  {
    name: 'labelEn',
    label: '英文',
  },
  {
    name: 'value',
    label: '值',
  },

];

interface DataItem {
  label: string;
  value: string;
  key?: string;
}

interface IProps {
  editInModal?: boolean;
  otherProps?: string;
  showDefault?: boolean;//展示默认值
  isDefaultAll?: boolean;//默认值可否多选
  formItems?: { name: string; label: string; type?: string; options?: any; }[];
  formExtra?: (values: any, setValues: Function) => React.ReactNode;
  changeControlProps(k: string, value: any, merge?: boolean): void;
  options?: { dataSource?: DataItem[]; };
  name?: string;
  mustOne?: boolean;
}

const initV = { width: 100, fixed: false };

const SelectDateSourceControll = ({ options, changeControlProps, showDefault, isDefaultAll, otherProps, editInModal, name, formItems: _formItems, formExtra, mustOne }: IProps) => {

  const formRef = useRef<FormxRefProps>(null);

  const [visible, setVisible] = useState(false);
  const [index, setIndex] = useState(0);
  const [initialValues, setInitialValues] = useState<any>(initV);

  const dataSource = options && options.dataSource ? options.dataSource || [] : [];

  const _changeControlProps = useCallback(
    (dataSource: DataItem[]) => {
      otherProps
        ? changeControlProps(
          otherProps,
          {
            ...options,
            [dataSourceKey]: dataSource,
          },
          true
        )
        : changeControlProps(dataSourceKey, dataSource);
    },
    [changeControlProps, options, otherProps]
  );

  const remove = useCallback(
    (index: number) => {
      _changeControlProps(
        update(dataSource, {
          $splice: [[index, 1]],
        })
      );
    },
    [_changeControlProps, dataSource]
  );

  const onOk = async () => {
    const res = await formRef?.current?.getFieldsValue();

    setVisible(false);
    _changeControlProps(
      dataSource.map((item, i) => i === index ? { ...initialValues, ...res } : item)
    );
  };

  const add = useCallback(() => {
    _changeControlProps(
      update(dataSource, {
        $push: [createDataItem(dataSource)],
      })
    );
  }, [_changeControlProps, dataSource]);

  const change = useCallback(
    (index: number, k: string, v: string | boolean, isClearOther?: boolean) => {
      _changeControlProps(
        isClearOther ? dataSource.map((item, i) => (
          index === i ? { ...item, [k]: v } : { ...item, [k]: false }
        )) : update(dataSource, {
          [index]: {
            [k]: {
              $set: v,
            },
          },
        })
      );
    },
    [_changeControlProps, dataSource]
  );

  const move = useCallback(
    (draggedId: string, hoverId: string) => {
      let draggedIndex: number = 0,
        hoverIndex: number = 0;

      dataSource.forEach((item, index) => {
        if (item.key === draggedId) draggedIndex = index;
        if (item.key === hoverId) hoverIndex = index;
      });

      _changeControlProps(
        update(dataSource, {
          $splice: [
            [draggedIndex, 1],
            [hoverIndex, 0, dataSource[draggedIndex]],
          ],
        })
      );
    },
    [_changeControlProps, dataSource]
  );

  const editInModalFn = useCallback((item: LineProps, index: number) => {
    setVisible(true);
    setIndex(index);
    item.width = item.width || initV.width;
    item.fixed = item.fixed || initV.fixed;
    setInitialValues({ ...item });
  }, []);

  return (
    <FormItem label={`${name || '选项'}内容`}>
      <ul className={styles.options}>
        {dataSource.map((item, i) => (
          <OptionSettingItem
            showRemore={mustOne ? dataSource.length > 1 : true}
            showDefault={showDefault}
            isDefaultAll={isDefaultAll}
            remove={remove}
            change={change}
            move={move}
            editInModal={editInModal ? editInModalFn : undefined}
            originalIndex={i}
            key={item.key}
            item={item} />
        ))}
      </ul>
      <p />
      <Button className={styles.btnStyle} icon={<Icon icon="&#xe635;" />} block onClick={add}>
        添加
      </Button>

      <Modal title='编辑列' onOk={onOk} destroyOnClose visible={visible} onCancel={() => setVisible(false)} width={500} bodyStyle={{ height: '50vh', overflow: 'auto' }}>
        <Formx groupNumber={1} ref={formRef} formItems={formItems.concat(_formItems || [])} initialValues={initialValues} />
        {formExtra?.(initialValues, setInitialValues)}
      </Modal>
    </FormItem>
  );
};

export default SelectDateSourceControll;
